package com.liuguangzhou.service.impl;

import com.liuguangzhou.model.User;
import com.liuguangzhou.service.UserService;
import com.liuguangzhou.utils.JadisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.HashMap;
import java.util.Map;

/**
 * @Classname UserService
 * @Author liuguangzhou
 * @Date 2020-04-06
 */
@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private JedisPool jedisPool;
    @Autowired
    private JadisUtil jadisUtil;


    /**
     * #################TODO String类型演示
     * @param key
     * @return
     */
    @Override
    public String getString(String key) {
        String value;
        Jedis resource = jedisPool.getResource();
        if (resource.exists(key)){
            log.info("从Redis中查询");
            value=resource.get(key);
        }else {
            log.info("从数据库中查询");
            value="刘广周Redis测试";
            resource.set(key,value);
        }
        resource.close();
        return value;
    }

    @Override
    public void expireStr(String key, String valve) {
        Jedis jedis = jadisUtil.getJedis();
        jedis.set(key,valve);
        jedis.expire(key,20);
        jadisUtil.closeJedis(jedis);
    }




    /**
     * ###########TODO Hash类型演示
     */
    @Override
    public User getUserById(String id) {
        String key="user"+id;
        User user=new User();

        Jedis jedis = jadisUtil.getJedis();
        if (jedis.exists(key)){
            log.info("-----------从Redis中查询");

            Map<String, String> map = jedis.hgetAll(key);
            user.setId(map.get("id"));
            user.setUserName(map.get("userName"));
            user.setAge(Integer.parseInt(map.get("age")));

        }else {
            log.info("---------从数据库中查询");
            user.setId("0001");
            user.setUserName("刘广周");
            user.setAge(18);

            /**
             * @param h  用户实体 user
             * @param hk 用户主键 id
             * @param hv 整个对象
             */
            Map<String,String> map=new HashMap<>();
            map.put("id",user.getId());
            map.put("userName",user.getUserName());
            map.put("age",user.getAge().toString());
            jedis.hset(key,map);

        }

        return user;
    }

}
